//
// Created by Administrator on 2023-03-12.
//

#include "Triangle.h"
#include "LogUtil.h"
#include <stdlib.h>
Triangle::Triangle()
{

}

Triangle::~Triangle()
{
    if (mProgram)
    {
        //删除Program
        glUtil.DeleteProgram(mProgram);
    }
}

void Triangle::Init(AAssetManager*  pManager,const char* vShaderFileName,const char* fShaderFileName)
{
    //顶点着色器
    AAsset* vFile = AAssetManager_open(pManager,vShaderFileName, AASSET_MODE_BUFFER);
    size_t vShaderSize = AAsset_getLength(vFile);
    char* vContentBuff = (char*)malloc(vShaderSize);
    AAsset_read(vFile, vContentBuff, vShaderSize);
    LOGD("VSHADERS: %s",vContentBuff);
    AAsset_close(vFile);

    //片元着色器
    AAsset* fFile = AAssetManager_open(pManager,fShaderFileName, AASSET_MODE_BUFFER);
    size_t fShaderSize = AAsset_getLength(fFile);
    char* fContentBuff = (char*)malloc(fShaderSize);
    AAsset_read(fFile, fContentBuff, fShaderSize);
    LOGD("FSHADERS: %s",fContentBuff);
    AAsset_close(fFile);

    mProgram = glUtil.CreateProgram(vContentBuff, fContentBuff, mVertexShader, mFragmentShader);

    //释放
    free(vContentBuff);
    free(fContentBuff);
}

void Triangle::Draw()
{
    //顶点数据
    GLfloat vVertices[] = {
            0.0f,  0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            0.5f, -0.5f, 0.0f,
    };

    if(mProgram == 0)
        return;

    //使用Program
    glUseProgram(mProgram);

    //加载顶点数据
    glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof (GLfloat), vVertices);
    //启用顶点数据
    glEnableVertexAttribArray (0);
    //绘制三角形
    glDrawArrays (GL_TRIANGLES, 0, 3);
}